package domain;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class ClientSocketObject implements Runnable 
{
	
	private Socket socket;
	private Scanner input;
	private PrintWriter output;
	private String message = "";

	public ClientSocketObject(Socket client) {
		socket = client;
	}

	@Override
	public void run() {
		try {
			input = new Scanner(socket.getInputStream());
			output = new PrintWriter(socket.getOutputStream());
		
			while(true){
				checkConnection();
				
				if(!input.hasNext()){
					return;
				}else{
					message = input.nextLine();
					System.out.println(socket.getInetAddress().getHostName() + " said: " + message);
				}
			}
			
		}catch(IOException e){
			System.out.println("Error: " + e.getMessage());
		}

	}

	private void checkConnection() {
		if(!socket.isConnected()){
			for(int i = 0; i<ServerThread.clients.size();i++){
				if(ServerThread.clients.get(i) == socket){
					ServerThread.clients.remove(i);
					System.out.println(socket.getInetAddress().getHostName() + "disconnected.");
				}
			}
		}
		
	}

}
